from multiprocessing.pool import ThreadPool
from threading import Thread
from os.path import exists
from invidious import *
import requests
import time
import sys

from plugins.plugin import Plugin

sys.path.append("..")
from src.video import Video as RVideo
from src.channel import Channel
from src.playlist import Playlist

from src.utils import *
from src.config import Config
from src.history import History

class InvidiousSubscriptions(Plugin):

    def __init__(self, history: History=History(), config: Config=Config()) -> None:
        super().__init__(history, config)

        self.history = history
        self.config = config

        self.name = "[+] Invidious: Subscriptions"
        self.category = "Invidious"

        if exists(self.config.subs_path): self.SUBS_LIST = [i.strip('\n').split(',')[0] for i in open(self.config.subs_path)]
        else: self.SUBS_LIST = []
        self.subscriptions = list()
        self.sorted_sub_videos = list()
        self.subs = list()

        self.params = {}

        self.flag = "-isb"
        self.full_flag = "--ivsubs"
        self.flag_help = "show all subscribed channels"
        self.flag_action = "store_true"

    def load_subscription(self, authorId=""):
        chn = self.invidious.get_channel(authorId)
        while chn == None:
            time.sleep(1)
            chn = self.invidious.get_channel(authorId)
        chn.convert(Channel)
        self.subscriptions.append(chn)

    def load_subscriptions(self):
        #if len(self.subscriptions) > 0: return False
        self.subscriptions.clear()
        self.invidious.update_mirrors()

        pool = ThreadPool(processes=10)
        pool.map(self.load_subscription, self.SUBS_LIST)

        self.subscriptions = sort_channels_by_link_list(self.subscriptions, self.SUBS_LIST)     

    def get_subscriptions(self):
        self.load_subscriptions()
        subs = list()
        for sub in self.subscriptions:
            channel = sub
            latestVideos = list()
            for video in channel.latestVideos:
                if video == None: continue
                video.convert(RVideo)
                video.url = self.invidious.get_working_mirror() + "/watch?v=" + video.videoId
                video.isWatched = video.in_history(self.history)
                latestVideos.append(video.to_json())

            channel.latestVideos = latestVideos
            subs.append(channel.to_json())

        return subs

    def get_items(self, params):
        return self.get_subscriptions()





